<template>
  <div v-loading="loading" class="Pack">
    <h4>打包活动</h4>
    <div class="key-search">
      <el-form ref="form" :rules="rules" :model="BindForm" label-width="80px" label-position="left">
        <el-form-item prop="actName" label="活动名称:">
          <el-col :span="24">
            <el-input v-model="BindForm.actName" placeholder="请输入活动名称" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item prop="actType" label="活动类型:">
          <el-col :span="24">
            <el-radio-group v-model="BindForm.actType" @change="reloadTableData">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="0">推荐活动</el-radio-button>
              <el-radio-button label="1">组合活动</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item prop="time" label="活动时间:">
          <el-col :span="24">
            <el-date-picker
              v-model="BindForm.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="center"
              clearable
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            />
            <el-button plain style="margin-left:10px" @click="setWeek">近一周</el-button>
            <el-button plain @click="setMonth">近一月</el-button>
            <el-button plain @click="setYear">近一年</el-button>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="key-type">
      <el-radio-group v-model="BindForm.state" @change="reloadTableData">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="0">上线</el-radio-button>
        <el-radio-button label="1">下线</el-radio-button>
        <el-radio-button label="2">已结束</el-radio-button>
      </el-radio-group>
      <el-button
        type="primary"
        @click="$router.push({ name: 'addPack' })"
      >新增打包活动</el-button>
    </div>
    <div class="ele-table">
      <el-table :data="BindTable" border max-height="600" :empty-text="loading ? '数据加载中' : (isSearch ? '未找到相关的打包活动' : '暂无打包活动')" @selection-change="handleSelectionChange">
        <el-table-column :selectable="selectable" type="selection" fixed="left" width="40" :resizable="false" />
        <el-table-column
          label="活动名称"
          prop="actName"
          align="center"
          min-width="200"
          :resizable="false"
          fixed="left"
        />
        <el-table-column
          label="活动类型"
          prop="state"
          align="center"
          width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.actType == 1" type="primary" size="small">组合活动</el-tag>
            <el-tag v-else-if="scope.row.actType == 0" type="success" size="small">推荐活动</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="累计参与购买人数"
          prop="buyUserCount"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="开始时间"
          prop="startTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="结束时间"
          prop="endTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="活动状态"
          prop="state"
          align="center"
          width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state == 2" type="info" size="small">已结束</el-tag>
            <el-tag v-else-if="scope.row.state == 1" type="info" size="small">下线</el-tag>
            <el-tag v-else-if="scope.row.state == 0" type="success" size="small">上线</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上线时间"
          prop="onlineTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          fixed="right"
          width="170"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row.state == 0" type="text" @click="lowRow([scope.row])">下线</el-button>
            <el-button v-else-if="scope.row.state == 1" type="text" @click="upRow([scope.row])">上线</el-button>
            <el-button type="text" @click="$router.push({name:'ActiveDetail', query: { p: $ed(scope.row) }})">查看详情</el-button>
            <el-button type="text" @click="deleteRow([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <div>
        <div v-if="selectedList && selectedList.length > 0" style="display: inline-flex;">
          <el-button size="mini" type="info" @click="lowRow(selectedList)">下线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="success" @click="upRow(selectedList)">上线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="danger" @click="deleteRow(selectedList)">删除（{{ selectedList.length }}）</el-button>
        </div>
      </div>
      <el-pagination
        background
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="limit"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="pageSizeChange"
        @current-change="currentPageChange"
      />
    </div>
  </div>
</template>

<script>
import { packList, changePackActState, deletePackAct } from '@/api/market'
import { Loading } from 'element-ui'
/** 打包活动 */
export default {
  name: 'Pack',
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      isSearch: false,
      BindForm: {
        actName: null,
        time: null,
        actType: 'all',
        state: 'all'
      },
      rules: {
      },
      BindTable: [],
      selectedList: []
    }
  },
  created() {
    const vm = this
    vm.loadTableData()
  },
  methods: {
    resetForm() {
      const vm = this
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    search() {
      const vm = this

      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.reloadTableData()
        }
      })
    },
    setWeek() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd HH:mm:ss'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd HH:mm:ss')
      ]
    },
    setMonth() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd HH:mm:ss'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd HH:mm:ss')
      ]
    },
    setYear() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 364)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd HH:mm:ss'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd HH:mm:ss')
      ]
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.reloadTableData()
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.loadTableData()
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    selectable(row, index) {
      if (row['state'] === 0 || row['state'] === 1) {
        return true
      }
      return false
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = {
        page: vm.page,
        limit: vm.limit
      }

      if (vm.BindForm.actName && vm.BindForm.actName.length > 0) {
        data['actName'] = vm.BindForm.actName
        vm.isSearch = true
      }

      if (vm.BindForm.actType !== 'all') {
        data['actType'] = parseInt(vm.BindForm.actType)
        vm.isSearch = true
      }

      if (vm.BindForm.state !== 'all') {
        data['state'] = parseInt(vm.BindForm.state)
        vm.isSearch = true
      }

      if (vm.BindForm.time && vm.BindForm.time.length === 2) {
        data['actTimes'] = {
          startTime: vm.BindForm.time[0],
          endTime: vm.BindForm.time[1]
        }
        vm.isSearch = true
      }

      vm.loading = true
      packList(data).then(res => {
        vm.loading = false
        vm.total = res.data.data.total
        vm.BindTable = res.data.data.data ? res.data.data.data : []
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    deleteRow(list) {
      const vm = this

      let msg = '确定删除【' + list[0]['actName'] + '】打包活动吗？'
      if (list.length > 1) {
        msg = '确定批量删除选中的【' + list.length + '】个打包活动吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        deletePackAct({
          idList: vm.$XEUtils.pluck(list, 'id')
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('删除打包活动成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    lowRow(list) {
      const vm = this

      let msg = '确定下线【' + list[0]['actName'] + '】打包活动吗？'
      if (list.length > 1) {
        msg = '确定批量下线选中的【' + list.length + '】个打包活动吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changePackActState({
          idList: vm.$XEUtils.pluck(list, 'id'),
          type: 1
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('下线打包活动成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    upRow(list) {
      const vm = this

      let msg = '确定上线【' + list[0]['actName'] + '】打包活动吗？'
      if (list.length > 1) {
        msg = '确定批量上线选中的【' + list.length + '】个打包活动吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changePackActState({
          idList: vm.$XEUtils.pluck(list, 'id'),
          type: 0
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('上线打包活动成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
  .Pack {
    padding: 30px;
    .key-search {
      padding: 20px 30px;
      padding-bottom: 0px;
      margin-bottom: 30px;
      border: 1px solid #eeeeee;
      .cus-input {
        max-width: 400px;
      }
    }
    .key-type {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 30px;
    }
    .ele-table,
    .pagination {
      margin-bottom: 30px;
    }
    .pagination {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
</style>
